package com.naizhuai.ui.dynamic;


import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.naizhuai.Model.AccountHelper;
import com.naizhuai.R;
import com.naizhuai.network.NetWorkObserver;
import com.naizhuai.network.apistore.apistoreiml.CommonManagerIml;
import com.naizhuai.ui.BaseFragment;
import com.naizhuai.ui.components.MultStateView;
import com.naizhuai.ui.entity.User.UserNews;
import com.naizhuai.util.NaizhuAILog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * A simple {@link Fragment} subclass.
 */
public class DynamicFragment extends BaseFragment {
    //    @BindView(R.id.task_tab)
//    TabLayout tabLayout;
//    @BindView(R.id.task_pager)
//    ViewPager viewPager;
    Unbinder unbinder;
    @BindView(R.id.container_State)
    MultStateView ContainerState;

    @BindView(R.id.news_list)
    RecyclerView newsList;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private NewListAdapter mNewListAdapter;
    private List<UserNews> mOldDatas;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        NaizhuAILog.d("onAttach");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        NaizhuAILog.d("onDetach");
    }

    private List<String> mTitles;
    private List<Fragment> fragmentList;

    public DynamicFragment() {
        // Required empty public constructor
    }

    public static DynamicFragment newInstance() {
        DynamicFragment fragment = new DynamicFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dynamic, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (TextUtils.isEmpty(AccountHelper.getComPanyid())) {
            ContainerState.showView(MultStateView.STATUS_EMPTY);
        } else {
            if (mOldDatas==null){
                refreshLayout.autoRefresh();
            }
            ContainerState.showView(MultStateView.STATUS_CONTENT);
        }
    }

    private void initAdapter() {
        FragmentPagerAdapter pageAdapter = new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getCount() {
                return fragmentList.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return mTitles.get(position);
            }

        };
//        viewPager.setAdapter(pageAdapter);
    }

    private void initFragment() {
        mTitles = Arrays.asList(getResources().getStringArray(R.array.study_string));
        fragmentList = new ArrayList();
        fragmentList.add(TempFragment.newInstance());
        fragmentList.add(TempFragment1.newInstance());
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        newsList.setLayoutManager(new LinearLayoutManager(getActivity()));
        newsList.setItemAnimator(new DefaultItemAnimator());
        newsList.setAdapter(mNewListAdapter = new NewListAdapter());
        refreshLayout.setEnableLoadmore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                loadNewsData();
            }
        });
//        initFragment();
//        initAdapter();
//        tabLayout.setupWithViewPager(viewPager);
    }

    private void loadNewsData() {
        CommonManagerIml.getInstance().article_list()
                .subscribe(new NetWorkObserver<List<UserNews>>() {
                    @Override
                    protected void onFail(String errormsg) {
                        if (refreshLayout!=null){
                            refreshLayout.finishRefresh();
                        }
                        shortToast(errormsg);
                    }
                    @Override
                    protected void onSuccess(List<UserNews> result) {
                        if (refreshLayout.isRefreshing()){
                            refreshLayout.finishRefresh();
                        }
                        if (mOldDatas == null) {
                            if (result.size() > 0) {
                                mOldDatas = result;
                                mNewListAdapter.setResult(mOldDatas);
                                mNewListAdapter.notifyDataSetChanged();
                                ContainerState.showView(MultStateView.STATUS_CONTENT);
                            } else {
                                ContainerState.showView(MultStateView.STATUS_NOMSG);
                            }

                        } else {
                            DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DiffCallBack(mOldDatas, result), true);
                            diffResult.dispatchUpdatesTo(mNewListAdapter);
                            mNewListAdapter.setResult(result);
                            mOldDatas = result;
                        }
                    }
                });
    }


    class DiffCallBack extends DiffUtil.Callback {
        private List<UserNews> mOldDatas, mNewDatas;

        public DiffCallBack(List<UserNews> mOldDatas,
                            List<UserNews> mNewDatas) {
            this.mOldDatas = mOldDatas;
            this.mNewDatas = mNewDatas;
        }

        @Override
        public int getOldListSize() {
            return mOldDatas != null ? mOldDatas.size() : 0;
        }

        @Override
        public int getNewListSize() {
            return mNewDatas != null ? mNewDatas.size() : 0;
        }

        @Override
        public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
            return mOldDatas.get(oldItemPosition).title
                    .equals(mNewDatas.get(newItemPosition).title);
        }

        @Override
        public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
            return false;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

}
